package com.yicong.ants.ui.video.adapter

import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.blankj.utilcode.util.ToastUtils
import com.x.livesdk.Room
import com.yicong.ants.ui.video.live.LiveItemFragment

class LiveViewpagerAdapter(val fragment: Fragment) : FragmentStateAdapter(fragment) {
    val liveItems: ArrayList<Room> = arrayListOf()
    private var preSelectedPosition = 0
    var onLiveAllCompletionListener: (() -> Unit)? = null
    override fun getItemCount(): Int {
        return liveItems.size
    }

    override fun getItemId(position: Int): Long {
        if (position < 0) {
            return position.toLong()
        }
        return try {
            val liveItem = liveItems[position]
            liveItem.live_number.toLong() + liveItem.LiveUrl.hashCode()
        } catch (e: Throwable) {
            position.toLong()
        }
    }

    override fun createFragment(position: Int): Fragment {
        val fragment = LiveItemFragment.create(liveItems[position])
        fragment.onLiveCompletionListener = {
            if (liveItems.size == 1) {
                onLiveAllCompletionListener?.invoke()
                ToastUtils.showLong("暂时没有直播了,请稍后再来~")
            }
        }
        return fragment
    }

    fun setNewData(newLiveItems: List<Room>) {
        val size = liveItems.size
        liveItems.clear()
        notifyItemRangeRemoved(0, size)
        liveItems.addAll(newLiveItems)
        notifyItemRangeInserted(0, liveItems.size)
    }

    fun setPageSelected(position: Int) {
        if (preSelectedPosition != -1) {
            val liveItemFragment = getPageFragment(getItemId(preSelectedPosition))
            if (liveItemFragment?.isCompletion() == true) {
                removeData(preSelectedPosition)
            } else {
                liveItemFragment?.unselected()
            }
        }
        getPageFragment(getItemId(position))?.play()
        preSelectedPosition = position
    }

    private fun removeData(position: Int) {
        liveItems.removeAt(position)
        notifyItemRemoved(position)
    }

    private fun getPageFragment(id: Long): LiveItemFragment? {
        return fragment.childFragmentManager.findFragmentByTag("f$id") as? LiveItemFragment
    }

    fun addData(newItems: ArrayList<Room>) {
        val start = liveItems.size
        liveItems.addAll(newItems)
        notifyItemRangeInserted(start, newItems.size)
    }

//    fun stopAll() {
//        for (i in 0..itemCount) {
//            val liveItemFragment = getPageFragment(getItemId(preSelectedPosition))
//            liveItemFragment?.pause()
//        }
//    }
}
